package com.hanbang.gycatering.aboutme;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.hanbang.gangyu.R;
import com.hanbang.gycatering.application.MyApplication;
import com.hanbang.gycatering.bean.PropertyBeanData;
import com.hanbang.gycatering.homepage.BaseActivity;
import com.hanbang.gycatering.property.FixDetail;
import com.hanbang.gycatering.property.FixRecord;
import com.hanbang.gycatering.utils.HttpInterfaces;
import com.hanbang.gycatering.utils.MyLog;
import com.hanbang.gycatering.utils.MyRequestCallBack;
import com.hanbang.gycatering.utils.MyToast;
import com.hanbang.gycatering.utils.PagingHelp;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class FeedBackRecord extends BaseActivity implements OnClickListener {
	private ArrayList<PropertyBeanData> feedbackDatas = new ArrayList<PropertyBeanData>();
	private PullToRefreshListView fbrlistview;
	private Myadapter myadapter;
	private PagingHelp pagingHelp = new PagingHelp();
	private TextView mDeleteRl, editTextView;
	private CheckBox mSelectAll;
	private RelativeLayout rl_delete;
	private boolean mIsDeleteModel = false;
	private boolean mIsSelectAll = false;
//	所有已维修的个数
	private int fixedcount=0;
	// 被选中的个数
		private int selectCount = 0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		initAnim();
		setContentView(R.layout.feedbackrecord);
		initView();
		setTheClick();
	}

	private void initView() {
		// TODO Auto-generated method stub
		((TextView) findViewById(R.id.top_bar_title)).setText("意见记录");
		setBackArrows((ImageView) findViewById(R.id.top_bar_left_image));
		fbrlistview = (PullToRefreshListView) findViewById(R.id.fbrlistview);
		mSelectAll = (CheckBox) findViewById(R.id.tv_select_all);
		editTextView = (TextView) findViewById(R.id.right_text);
		mDeleteRl = (TextView) findViewById(R.id.main_delete_rl);
		rl_delete = (RelativeLayout) findViewById(R.id.rl_delete);
		editTextView.setVisibility(View.VISIBLE);
		editTextView.setText("编辑");
		myadapter = new Myadapter(feedbackDatas);
		fbrlistview.setAdapter(myadapter);
		getFeedBackDatas();
		fbrlistview.setMode(Mode.BOTH);
		
	}
	private void setTheClick() {
		setBackArrows((ImageView) findViewById(R.id.top_bar_left_image));
		// 编辑全选
		mSelectAll.setOnClickListener(this);
		mDeleteRl.setOnClickListener(this);
		editTextView.setOnClickListener(this);
		 
		fbrlistview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				if (mIsDeleteModel) {
					addDeleteDog(position - 1);
				} else {
					Intent intent = new Intent(FeedBackRecord.this, FeedDetail.class);
					intent.putExtra("feedbackId", feedbackDatas.get(position-1).getId());
					intent.putExtra("replystate", feedbackDatas.get(position-1).getState());
					startActivity(intent);
				}
				// TODO Auto-generated method stub
			}
		});
		fbrlistview.setOnRefreshListener(new OnRefreshListener2<ListView>() {
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
				// TODO Auto-generated method stub
				feedbackDatas.clear();
				pagingHelp.clear();
				getFeedBackDatas();
			}
			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
				// TODO Auto-generated method stub
				getFeedBackDatas();
			}
		}); 
	}

	private void getFeedBackDatas() {
		// TODO Auto-generated method stub
		((MyApplication) getApplicationContext()).httpUtils.send(
				HttpMethod.GET,
				HttpInterfaces.feedlist + "&userphone="
						+ userData.getUserphone() + "&password="
						+ userData.getUserpassword() + "&PageIndex="
						+ pagingHelp.getPageindex(),
				new MyRequestCallBack<String>(FeedBackRecord.this,
						getString(R.string.loadding)) {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(
									responseInfo.result);
							if (json.getInt("state") == 1) {
								pagingHelp.setRecordCount(json
										.getInt("recordCount"));
								pagingHelp.setPageCount(json
										.getInt("pageCount"));
								JSONArray info = json.getJSONArray("info");
								int j = 0;
								for (j = pagingHelp.getCurrentCount(); j < info
										.length(); j++) {
									PropertyBeanData pbdata = new PropertyBeanData();
									pbdata.setId(info.getJSONObject(j).getInt(
											"id"));
									pbdata.setTitle(info.getJSONObject(j)
											.getString("title"));
									pbdata.setState(info.getJSONObject(j)
											.getBoolean("isreply"));
									if(info.getJSONObject(j).getBoolean("isreply")){
										fixedcount++;
									}
									feedbackDatas.add(pbdata);
								}
								pagingHelp.isNextPaging(FeedBackRecord.this,
										info.length(), j);
							} else {
								pagingHelp.showNoData(FeedBackRecord.this);
							}
							myadapter.notifyDataSetChanged();
						} catch (JSONException e) {
							e.printStackTrace();
							MyToast.show(FeedBackRecord.this, "获取数据失败",
									Toast.LENGTH_SHORT);
						}
						fbrlistview.onRefreshComplete();
					}
				});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.tv_select_all:
			if (mSelectAll.isChecked()) {
				addDeleteAllDogs();
			} else {
				clearCheckItem();
			}
			break;
		case R.id.main_delete_rl:
			deleteCheckItem();
			hideDeleteModel();
			break;
		case R.id.right_text:
			showDeleteModel();

			break;
		default:
			break;
		}
	}
	// 清空全部
	private void clearCheckItem() {
		Iterator<PropertyBeanData> iterator = feedbackDatas.iterator();
		while (iterator.hasNext()) {
			PropertyBeanData pbd = iterator.next();
			pbd.setChecked(false);
		}
		myadapter.setDatas(feedbackDatas);
		myadapter.showDeleteCheckBox();
		mIsDeleteModel = true;
		mIsSelectAll = false;
	}

	// 删除
	private void deleteCheckItem() {
		MyLog.e("deleteCheckItem", HttpInterfaces.feeddelete + "&password="
						+ userData.getUserpassword() + "&userphone="
						+ userData.getUserphone() + "&idval="
						+ getSeleteId());
		((MyApplication) getApplicationContext()).httpUtils.send(
				HttpMethod.GET, HttpInterfaces.feeddelete + "&password="
						+ userData.getUserpassword() + "&userphone="
						+ userData.getUserphone() + "&idval="
						+ getSeleteId(), new MyRequestCallBack<String>(
								FeedBackRecord.this, getString(R.string.loadding)) {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(
									responseInfo.result);
							int state = json.getInt("state");
							if (state == 1) {
								MyToast.show(FeedBackRecord.this, "删除成功", Toast.LENGTH_SHORT);
								feedbackDatas.clear();
								pagingHelp.clear();
								getFeedBackDatas();
							} else if (state == -100) {
								passwordIsError(false);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}

					}
				});
//		Iterator<PropertyBeanData> iterator = fixDatas.iterator();
//		int count = 0;
//		while (iterator.hasNext()) {
//			PropertyBeanData pbd = iterator.next();
//			if (pbd.isChecked()) {
//				count++;
//				iterator.remove();
//			}
//		}
//		MyToast.show(FeedBackRecord.this, "删除了" + count + "条", Toast.LENGTH_SHORT);
	}

	// 添加删除item
	private void addDeleteDog(int position) {
		PropertyBeanData pbd = (PropertyBeanData) feedbackDatas.get(position);
		if (pbd.isChecked()) {
			pbd.setChecked(false);
		} else {
			pbd.setChecked(true);
		}
		myadapter.setDatas(feedbackDatas);
		myadapter.showDeleteCheckBox();
		mIsDeleteModel = true;
	}

	// 全部选中
	private void addDeleteAllDogs() {
		Iterator<PropertyBeanData> iterator = feedbackDatas.iterator();
		while (iterator.hasNext()) {
			PropertyBeanData pbd = iterator.next();
			if(pbd.getState()){
				pbd.setChecked(true);
			}
			
		}
		myadapter.setDatas(feedbackDatas);
		myadapter.showDeleteCheckBox();
		mIsDeleteModel = true;
		mIsSelectAll = true;
	}
	// 展示编辑模式
		private void showDeleteModel() {
			mSelectAll.setChecked(false);
			mIsDeleteModel = true;
			editTextView.setVisibility(View.GONE);
			setAnim();
			// PropertyBeanData pbd = (PropertyBeanData) fixDatas.get(position);
			// pbd.setChecked(true);
			myadapter.setDatas(feedbackDatas);
			myadapter.showDeleteCheckBox();
			
		}

	// 隐藏编辑模式，回到正常显示listView
	private void hideDeleteModel() {
		mIsDeleteModel = false;
		editTextView.setVisibility(View.VISIBLE);
		setAnim();
		Iterator<PropertyBeanData> iterator = feedbackDatas.iterator();
		while (iterator.hasNext()) {
			PropertyBeanData pbd = iterator.next();
			pbd.setChecked(false);
		}
		myadapter.hideDeleteCheckBox();
		myadapter.notifyDataSetChanged();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (myadapter == null) {
			return super.onKeyDown(keyCode, event);
		}
		if (keyCode == KeyEvent.KEYCODE_BACK && mIsDeleteModel) {
			hideDeleteModel();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public class Myadapter extends BaseAdapter {
		PropertyBeanData entity;
		Bitmap bit;

		private List<PropertyBeanData> coll;
		private boolean mIsShowDeleteCheckBox;

		public Myadapter(List<PropertyBeanData> coll) {
			this.coll = coll;
		}

		public void setDatas(List<PropertyBeanData> colls) {
			this.coll = colls;
		}

		public int getCount() {
			return coll.size();
		}

		public Object getItem(int position) {
			return coll.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		@SuppressLint("InflateParams") @Override
		public View getView(int position, View convertView, ViewGroup parent) {
			MyLog.e("getView", position + "");
			ViewHolder holder = null;
			PropertyBeanData data = coll.get(position);
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = getLayoutInflater().inflate(
						R.layout.item_property, null);
				holder.title = (TextView) convertView
						.findViewById(R.id.item_left);
				holder.time = (TextView) convertView
						.findViewById(R.id.item_right);
				holder.cb = (CheckBox) convertView
						.findViewById(R.id.item_propertycb);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			if (mIsShowDeleteCheckBox) {
				holder.cb.setVisibility(View.VISIBLE);
				holder.cb.setChecked(coll.get(position).isChecked());
				if (coll.get(position).isChecked()) {
					if (selectCount < fixedcount) {
						selectCount++;
					}
				} else {
					if (selectCount > 0) {
						selectCount--;
					}
				}
				if (selectCount >= fixedcount) {
					selectCount = fixedcount;
					mSelectAll.setSelected(true);
				} else {
					mSelectAll.setSelected(false);
				}
			} else {
				holder.cb.setVisibility(View.GONE);
			}
			holder.title.setText(data.getTitle());
			if(data.getState()){
				holder.time.setTextColor(getResources().getColor(R.color.orange));
				holder.time.setText("已回复");
				
			}else{
				holder.time.setTextColor(getResources().getColor(R.color.black));
				holder.time.setText("待回复");
				if (mIsShowDeleteCheckBox) {
					holder.cb.setVisibility(View.INVISIBLE);
				} else{
					holder.cb.setVisibility(View.GONE);	
				}
			}
			return convertView;
		}

		private class ViewHolder {
			TextView title = null;
			TextView time = null;
			CheckBox cb;
		}

		public void showDeleteCheckBox() {
			mIsShowDeleteCheckBox = true;
			notifyDataSetChanged();
		}

		public void hideDeleteCheckBox() {
			mIsShowDeleteCheckBox = false;
		}
	}
	private Animation showAction = null, hiddenAction = null;
	private void initAnim() {
		showAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
				Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
				1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
		showAction.setDuration(150);
		hiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
				Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
				0.0f, Animation.RELATIVE_TO_SELF, 1.0f);
		hiddenAction.setDuration(150);
	}
	private void setAnim() {
		rl_delete.clearAnimation();
		if(mIsDeleteModel){
			rl_delete.setVisibility(View.VISIBLE);
			rl_delete.startAnimation(showAction);
		}else{
			rl_delete.setVisibility(View.GONE);
			rl_delete.startAnimation(hiddenAction);
		}
	}
//	获得ID字符串
	private String getSeleteId() {
		// 遍历出id 2,4,6
		StringBuilder id = new StringBuilder();

		for (PropertyBeanData data : feedbackDatas) {
			if (data.isChecked()) {
				id.append(data.getId() + ",");
			}
		}
		if (id.length() > 0) {
			id.delete(id.length() - 1, id.length());
		}
		MyLog.e("getSeleteId", id.toString());
		return id.toString();
	}
}
